package org.iss.ip.controller;

import javax.servlet.http.HttpSession;

import org.iss.ip.bean.User;
import org.iss.ip.service.SendCodeService;
import org.iss.ip.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户控制类
 * 
 * @author sen
 *
 */
@RestController
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private SendCodeService sendCodeService;

	@RequestMapping("get")
	public User get(String username) {
		return userService.findByUsername(username);
	}

	@RequestMapping("login")
	public String login(User user, HttpSession session) {
		System.out.println(user.getUsername());
		User user2 = get(user.getUsername());
		if (user2 != null) {
			if (user.getPassword().equals(user2.getPassword())) {
				session.setAttribute("LOGIN_INFO", user); // 将用户信息装入session中，便于以后判断用户是否登录
				session.setAttribute("user_id", user.getId());
				return "success";
			} else {
				return "failure";
			}
		} else {
			return "failure";
		}
	}

	/**
	 * 注册
	 * 
	 * @param user
	 * @param code
	 * @param session
	 * @return
	 */
	@RequestMapping("signup")
	public String signup(User user, HttpSession session) {
		// String sessionCode = (String) session.getAttribute("code");
		// if (sessionCode != null) {
		// if (code.equals(sessionCode)) {
		if (userService.findByUsername(user.getUsername()) != null) {
			userService.save(user);
			return "success";
		} else {
			return "failure";
		}
		// } else {
		// return "failure";
		// }
		// } else {
		// return "failure";
		// }

	}

	@RequestMapping("logout")
	public void logout(HttpSession session) {
		session.invalidate();
	}

	@RequestMapping("code")
	public String code(String phone, HttpSession session) {
		System.out.println(phone);
		if (!sendCodeService.isChinaPhoneLegal(phone) && !sendCodeService.isHKPhoneLegal(phone)) {
			return "failure";
		}
		try {
			String code = sendCodeService.randCode();
			System.out.println(code);
			sendCodeService.sendCode(phone);
			session.setAttribute("code", code);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "success";
	}

}
